//
//  ShareData.m
//  Staff
//
//  Created by caiyao on 12/12/14.
//
//

#import "ShareData.h"
#import "Config.h"

@implementation ShareData
static ShareData *shareInstance = nil;
static NSString *lastConfigUpdateDateKey = @"lastConfigUpdateDateKey";
static NSString *appStateKey = @"appStateKey";

+ (ShareData*) shareInstance {
    @synchronized([ShareData class]) {
        if (shareInstance == nil)
        {
            shareInstance = [[self alloc] init];
            
        }
        return shareInstance;
    }
}

/*
 The Methods should not changed.
 */
+ (id)alloc {
    @synchronized([ShareData class]) {
        shareInstance = [super alloc];
        return shareInstance;
    }
    
    return nil;
}

+ (id)allocWithZone:(NSZone *)zone {
    @synchronized([ShareData class]) {
        shareInstance= [super allocWithZone:zone];
        return shareInstance;
    }
    return nil;
}

- (id)init {
    if (self = [super init]) {
        volatileDic = [[NSMutableDictionary alloc] init];
    }
    
    return self;
}

- (void)vSetter:(NSString *)key value:(NSString *)value {
    [volatileDic setObject:value forKey:key];
}

- (NSString *)vGetter:(NSString *)key {
    return [volatileDic objectForKey:key];
}

- (Config *)getConfig {
    Config *config = nil;
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"config"]) {
        config = [Config parserConfigObjectWithJson:[[NSUserDefaults standardUserDefaults] objectForKey:@"config"]] ;
    }
    return config;
}

- (void)setLastConfigUpdateDate {
    [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:lastConfigUpdateDateKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (BOOL)configUpToDate {
    NSDate *currentDate = [NSDate date];
    NSDate *lastUpdateDate = [[NSUserDefaults standardUserDefaults] objectForKey:lastConfigUpdateDateKey];
    int configUpdatePeroid = [[ShareData shareInstance] getConfig].configUpdatePeriodInHours;
    if ([currentDate timeIntervalSinceDate:lastUpdateDate] > 60*60*configUpdatePeroid) {
        return YES;
    }
    return NO;
}

- (void)setAppState:(AppState)state {
    [[NSUserDefaults standardUserDefaults] setInteger:state forKey:appStateKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (AppState)getAppState {
    return [[NSUserDefaults standardUserDefaults] integerForKey:appStateKey];
}

@end
